package cdu.hjx.project.sys.handler;

import cdu.hjx.project.pojo.Role;
import cdu.hjx.project.sys.service.RoleService;
import cdu.hjx.project.utils.CommonResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/role")
public class RoleHandler {

    @Resource
    private RoleService roleService;

    /**
     * 添加角色
     * @param role 角色信息
     * @return CommonResult 统一返回类
     */
    @PostMapping("/add")
    public CommonResult addRole(@RequestBody Role role) {
        System.out.println(">>>>>>>>>>>>"+role);
        try {
            int insert = roleService.insert(role);
            if (1 == insert) {
                return CommonResult.success(role);
            }
            if (0 == insert) {
                return CommonResult.error(201, "添加角色失败");
            }
            if (-1 == insert) {
                return CommonResult.error(-1, "您要添加的角色已经存在,请换一个.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error(500, "添加角色失败");
        }
        return null;
    }

    /**
     * 获取角色列表
     * @param pageNum 页码
     * @param pageSize 每页记录数
     * @return CommonResult 统一返回类
     */
    @GetMapping("/roles/{pageNum}/{pageSize}")
    public CommonResult<PageInfo<Role>> roles(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize) {
        try {
            PageHelper.startPage(pageNum, pageSize);
            List<Role> roles = roleService.roles();
            PageInfo<Role> pageInfo = new PageInfo<>(roles);
            return null != roles ? CommonResult.success(pageInfo) : CommonResult.error(201, "请求成功,没有查询到角色数据.");
        } catch (Exception e) {
            return CommonResult.error(500, "系统异常,获取角色列表数据失败,请联系管理员.");
        }
    }
}